package com.example.week12;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtils {
    private static String user = "root";// 用户名
    private static String password = "mypassword"; //密码
    private static Connection getConn(String dbName) {
        Connection connection = null;
        try {
            //动态加载 MySql 的驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 连接数据库的地址，ip 不能写成 localhost，测试时手机和电脑连接的网络必须是同一个局域网
            // 在使用云端部署的数据库时，数据库服务器 ip 可以根据实际设置
            String url = "jdbc:mysql://192.168.0.104:3306/" + dbName;
            // 尝试建立到给定数据库 URL 的连接,参数涉及数据库 IP，端口，数据库名，账号及密码等
            connection = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
    public static ResultSet queryReader(String reader_num) {
        // 根据数据库名称，建立连接
        ResultSet rs = null;
        Connection connection = getConn("library");
        if (connection != null) {// connection 不为 null 表示与数据库建立了连接
            try {
                PreparedStatement ps;
                Statement smt = connection.createStatement();
                String sql = "select * from readers where reader_number LIKE '%" + reader_num + "%'";
                rs = smt.executeQuery(sql);
                //connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return rs;
    }
}
